package com.android.jianboshi.manager;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

import com.android.baselibrary.interface_.CommCallBack;

public class MedioPlayerUtil {

    MediaPlayer mediaPlayer;
    CommCallBack callBack;
    Context mContext;

    public MedioPlayerUtil(Context mContext, CommCallBack callBack) {
        mediaPlayer = new MediaPlayer();
        this.callBack = callBack;
        this.mContext = mContext;

        mediaPlayer.setVolume(100, 100);
    }

    public void setData(String path, boolean isLoop) {
        try {
            mediaPlayer.reset();
            AssetFileDescriptor fileDescriptor = mContext.getAssets().openFd(path);
            mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
            mediaPlayer.prepareAsync();//让MediaPlayer进入到准备状态
//            Log.i("test","数据加载");
            mediaPlayer.setLooping(isLoop);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //播放操作
//                    Log.i("test","数据加载完成，开始播放:"+ path);
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (callBack != null) {
//                        Log.i("test","播放完成");
                        callBack.onResult(null);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void release() {
        stop();
        mediaPlayer.release();
        mediaPlayer = null;
        callBack = null;
    }

    public void stop() {
        try {
            mediaPlayer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
